package com.testDemo.maven;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: zouren
 * @date: 2022/10/12
 * @description:
 */
public class UpMaven {
    //批量安装jar所在目录，不是使用中maven本地仓库的目录会有冲突
    public static String filePath = "D:\\java\\lib2";
    /**
     * 上传的地址正的或开发的
     */
    public static String url = "http://XXXX:XX/repository/XXXX-snapshot";
    /**
     *  这是你本地的的setting.xml文件需要存在这个ID,
     * 并配置你私服的账号密码的,否则会出现Not authorized , ReasonPhrase:Unauthorized.错误。
     */
    public static String repositoryId = "XXXXX-nexus-snapshots";
    public static List<GroupInfo> jarList=new ArrayList<>();

    public static void main(String[] args) {
        File f = new File(filePath);
        getJarList(f);
//        jarList.forEach(System.out::println);
        printFile();
    }

    /**
     *   <groupId>com.alibaba.cloud</groupId>
     *                 <artifactId>spring-cloud-alibaba-dependencies</artifactId>
     * @param file
     */
    private static void getJarList(File file) {
        if(file.isDirectory()){
            for (File listFile : file.listFiles()) {
                getJarList(listFile);
            }
        }else if(file.getName().endsWith(".jar")){
            GroupInfo groupInfo = new GroupInfo();
            groupInfo.version=file.getParentFile().getName();
            groupInfo.artifactId=file.getParentFile().getParentFile().getName();
            groupInfo.groupId=getGroupId(file);
            groupInfo.file=file;
            groupInfo.pomFile=getPomFile(file.getParentFile());
            jarList.add(groupInfo);
        }else if(file.getName().endsWith(".pom")){
            if(ifPomDir(file.getParentFile())){
                GroupInfo groupInfo = new GroupInfo();
                groupInfo.version=file.getParentFile().getName();
                groupInfo.artifactId=file.getParentFile().getParentFile().getName();
                groupInfo.groupId=getGroupId(file);
                groupInfo.isPom=true;
                groupInfo.pomFile=file;
                jarList.add(groupInfo);
            }
        }
    }

    private static boolean ifPomDir(File parentFile) {
        return !Arrays.stream(parentFile.listFiles()).anyMatch(f->f.getName().endsWith(".jar"));
    }
    private static File getPomFile(File parentFile) {
        return Arrays.stream(parentFile.listFiles()).filter(f->f.getName().endsWith(".pom")).findAny().get();
    }

    private static String getGroupId(File file) {
        String replace = file.getAbsolutePath().replace(filePath, "");
        String artifactId = file.getParentFile().getParentFile().getName();
        return replace.substring(1,replace.indexOf(artifactId)-1).replaceAll("\\\\",".");
    }

    /**
     * 功能：批量安装maven的本地的jar
     */
    public static void printFile() {
        jarList.forEach(jar->{
            System.out.println("导入jar到本地仓库"+jar);
            String sb =null;
            if(!jar.isPom){
                sb = "mvn deploy:deploy-file \"-DgroupId="+ jar.groupId+"\"" +
                        " \"-DartifactId="+ jar.artifactId+"\" " +
                        "\"-Dversion="+jar.version+"\" \"-Dpackaging=jar\"" +
                        " \"-Dfile="+jar.file.getAbsolutePath()+"\" " +
                        "\"-Durl="+url+"\"" +
                        " \"-DrepositoryId="+repositoryId+"\"" +
                        " \"-DpomFile="+jar.pomFile.getAbsolutePath()+"\"";
            }else{
                sb = "mvn deploy:deploy-file \"-DgroupId="+ jar.groupId+"\"" +
                        " \"-DartifactId="+ jar.artifactId+"\" " +
                        "\"-Dversion="+jar.version+"\" \"-Dpackaging=pom\"" +
                        " \"-Dfile="+jar.pomFile.getAbsolutePath()+"\" " +
                        "\"-Durl="+url+"\"" +
                        " \"-DrepositoryId="+repositoryId+"\"" ;
            }
            System.out.println(sb);
            execCommandAndGetOutput(sb);
        });
    }

    public static void execCommandAndGetOutput(String comond) {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("cmd.exe /c "+comond);
            // 输出结果，必须写在 waitFor 之前
            String outStr = getStreamStr(process.getInputStream());
            // 错误结果，必须写在 waitFor 之前
            String errStr = getStreamStr(process.getErrorStream());
            int exitValue = process.waitFor(); // 退出值 0 为正常，其他为异常
            System.out.println("exitValue: " + exitValue);
            System.out.println("outStr: " + outStr);
            System.out.println("errStr: " + errStr);
            process.destroy();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String getStreamStr(InputStream is) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        br.close();
        return sb.toString();
    }

    static class GroupInfo{
        String artifactId;
        String version;
        String groupId;
        Boolean isPom=false;
        File file;
        File pomFile;

        @Override
        public String toString() {
            return "GroupInfo{" +
                    "artifactId='" + artifactId + '\'' +
                    ", version='" + version + '\'' +
                    ", groupId='" + groupId + '\'' +
                    '}';
        }
    }
}
